package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.ContentTypeEnums;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ora.constant.BizConstants;
import com.ruoyi.ring.domain.RingDeviceAichat;
import com.ruoyi.ring.domain.VoiceTranModel;
import com.ruoyi.ring.domain.dto.DeviceAichatQueryDTO;
import com.ruoyi.ring.factory.AiFactory;
import com.ruoyi.ring.factory.VoiceTranslatFactory;
import com.ruoyi.ring.service.IRingDeviceAichatService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小A管家 app
 */
@RestController
@RequestMapping("/ring/app/ai")
public class LittleAButlerController extends BaseController {

    @Resource
    private IRingDeviceAichatService deviceAichatService;

    @Resource
    private ISysConfigService configService;
    /**
     * 小A管家 App
     * @param dto
     * @return
     */
    @PostMapping("/send")
    public AjaxResult send(DeviceAichatQueryDTO dto)
    {

        try {
            RingDeviceAichat deviceAichat = Convert.convert(RingDeviceAichat.class,dto);
            if(ContentTypeEnums.TEXT.getCode().equals(dto.getContentType())){
                if (deviceAichat.getDeviceContent() != null && !"".equals(deviceAichat.getDeviceContent())){
                    deviceAichat.setUserId(SecurityUtils.getUserId());
                    deviceAichatService.insertRingDeviceAichat(deviceAichat);
                    PageHelper.startPage(1,10, "id desc");
                    List<RingDeviceAichat> deviceAichats = deviceAichatService.selectRingDeviceAichatList(Builder.of(RingDeviceAichat::new)
                            .with(RingDeviceAichat::setDeviceSn, deviceAichat.getDeviceSn())
                            .build());
                    // 调用AI自动回复
                    deviceAichats = deviceAichats.stream().sorted(Comparator.comparingLong(RingDeviceAichat::getId)).collect(Collectors.toList());
                    RingDeviceAichat aichatReply = deviceAichatService.aichatAutoReply(deviceAichats);
                    if (aichatReply != null){
                        aichatReply.setUserId(SecurityUtils.getUserId());
                        deviceAichatService.insertRingDeviceAichat(aichatReply);
                    }
                    return AjaxResult.success(aichatReply);
                }
            }
            if(ContentTypeEnums.VOICE.getCode().equals(dto.getContentType())){
                MultipartFile file = dto.getFile();
                String filePath = RuoYiConfig.getUploadPath();
                String fileName = FileUploadUtils.upload(filePath, file);
                deviceAichat.setDeviceVoice(fileName);
                deviceAichat.setUserId(SecurityUtils.getUserId());
                // 把音频转写成文字
                VoiceTranModel voiceTranModel = VoiceTranslatFactory.build(BizConstants.TRAN_MODEL.getValue()).voiceTranslat(fileName.replace(Constants.RESOURCE_PREFIX, RuoYiConfig.getProfile()));
                if (voiceTranModel != null){
                    deviceAichat.setDeviceContent(voiceTranModel.getText());
                    deviceAichat.setDeviceDuration(voiceTranModel.getTotalDuration());
                    deviceAichatService.insertRingDeviceAichat(deviceAichat);
                    PageHelper.startPage(1,10, "id desc");
                    List<RingDeviceAichat> deviceAichats = deviceAichatService.selectRingDeviceAichatList(Builder.of(RingDeviceAichat::new)
                            .with(RingDeviceAichat::setDeviceSn, deviceAichat.getDeviceSn())
                            .build());
                    deviceAichats = deviceAichats.stream().sorted(Comparator.comparingLong(RingDeviceAichat::getId)).collect(Collectors.toList());
                    // 调用AI自动回复
                    RingDeviceAichat aichatReply = deviceAichatService.aichatAutoReply(deviceAichats);
                    if (aichatReply != null){
                        deviceAichatService.insertRingDeviceAichat(aichatReply);
                    }
                    return AjaxResult.success(aichatReply);
                }
            }

            if(ContentTypeEnums.IMAGE.getCode().equals(dto.getContentType())){
                String result = "";
                String fileName = "";
                Gson gson = new Gson();
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                fileName = FileUploadUtils.upload(filePath, dto.getFile());
                String apiHost = configService.selectConfigByKey("ring.api.host");
                result = AiFactory.build(BizConstants.AI_PLATFORM.getValue()).chatImageCompletions(
                        "基于图片请给出图片上内容汇总，并返回50字以内json格式内容。不要以makedown格式返回，只返回json格式，不要其他任何说明，json格式为{\"content\": \"xxx\"}",
                        apiHost + fileName);
                Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                String content = resultMap.get("content").toString();
                deviceAichat.setUserId(SecurityUtils.getUserId());
                if(!"".equals(deviceAichat.getDeviceContent()) && deviceAichat.getDeviceContent() != null){
                    content = deviceAichat.getDeviceContent() + "，" + content;
                }
                deviceAichat.setDeviceContent(content);
                deviceAichatService.insertRingDeviceAichat(deviceAichat);
                PageHelper.startPage(1,10, "id desc");
                List<RingDeviceAichat> deviceAichats = deviceAichatService.selectRingDeviceAichatList(Builder.of(RingDeviceAichat::new)
                        .with(RingDeviceAichat::setDeviceSn, deviceAichat.getDeviceSn())
                        .build());
                // 调用AI自动回复
                deviceAichats = deviceAichats.stream().sorted(Comparator.comparingLong(RingDeviceAichat::getId)).collect(Collectors.toList());
                RingDeviceAichat aichatReply = deviceAichatService.aichatAutoReply(deviceAichats);
                if (aichatReply != null){
                    aichatReply.setUserId(SecurityUtils.getUserId());
                    deviceAichatService.insertRingDeviceAichat(aichatReply);
                }
                return AjaxResult.success(aichatReply);
            }

            if(ContentTypeEnums.FILE.getCode().equals(dto.getContentType())){{

            }}


        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        return AjaxResult.error();
    }
}
